package activity.setting;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.hichip.callback.ICameraIOSessionCallback;
import com.hichip.campro.R;
import com.hichip.content.HiChipDefines;
import com.hichip.control.HiCamera;
import com.hichip.data.HiDeviceInfo;
import com.hichip.tools.Packet;
import com.tencent.android.tpush.XGPushConfig;
import java.util.regex.Pattern;
import base.HiActivity;
import bean.MyCamera;
import butterknife.BindView;
import common.CamHiDefines;
import common.HiDataValue;
import common.TitleView;
import custom.SwitchButton;
import custom.dialog.NiftyDialogBuilder;
import utils.HiToast;
import utils.HiTools;

public class AlarmManageAndNotiActivity extends HiActivity implements CompoundButton.OnCheckedChangeListener, ICameraIOSessionCallback, View.OnClickListener {
    @BindView(R.id.title) TitleView title;
    private MyCamera mMyCamera;

    @BindView(R.id.switch_btn_push) SwitchButton switch_btn_push;
    @BindView(R.id.switch_voice_alarm) SwitchButton switch_voice_alarm;//声音报警
    @BindView(R.id.switch_btn_vmd) SwitchButton switch_btn_vmd;//移动侦测报警
    @BindView(R.id.ll_content_device_alarm) LinearLayout ll_content_device_alarm;
    @BindView(R.id.rl_adjust_vmd) LinearLayout rl_adjust_vmd;
    @BindView(R.id.tv_sensitivity) TextView tv_sensitivity;

    private boolean mChecked = false;
    private final static int HANDLE_MESSAGE_BIND_SUCCESS = 0x80000001;
    private final static int HANDLE_MESSAGE_BIND_FAIL = 0x80000002;
    private final static int HANDLE_MESSAGE_UNBIND_SUCCESS = 0x80000003;
    private final static int HANDLE_MESSAGE_UNBIND_FAIL = 0x80000004;
    private HiChipDefines.HI_P2P_S_MD_PARAM md_param;
    private HiChipDefines.HI_P2P_S_ALM_PARAM voiceParam;

    @BindView(R.id.rl_alarm_snap_to_sdcard) RelativeLayout rl_alarm_snap_to_sdcard;//报警抓拍至SD卡
    @BindView(R.id.rl_alarm_video_to_sdcard) RelativeLayout rl_alarm_video_to_sdcard;//报警录像至SD卡
    @BindView(R.id.rl_alarm_video_to_ftp) RelativeLayout rl_alarm_video_to_ftp;//报警录像至FTP
    @BindView(R.id.ll_root_alarm_linkage) LinearLayout ll_root_alarm_linkage;
    @BindView(R.id.ll_alarm_linkage_content) LinearLayout ll_alarm_linkage_content;
    @BindView(R.id.switch_btn_alarm_linkage) SwitchButton switch_btn_alarm_linkage;//警号联动开关
    @BindView(R.id.tv_voice_type) TextView tv_voice_type;
    @BindView(R.id.tv_alarm_time) TextView tv_alarm_time;
    @BindView(R.id.rl_alarm_voice_type) RelativeLayout rl_alarm_voice_type;//警号类型
    @BindView(R.id.rl_alarm_time) RelativeLayout rl_alarm_time;// 警号时长
    @BindView(R.id.switch_alarm_snaptosdcard) SwitchButton switch_alarm_snaptosdcard;//报警抓拍至SD卡
    @BindView(R.id.switch_alarm_videotosdcard) SwitchButton switch_alarm_videotosdcard;//报警录像至SD卡
    @BindView(R.id.switch_alarm_snaptoemail) SwitchButton switch_alarm_snaptoemail;//报警抓怕发送至Email

    @BindView(R.id.switch_alarm_videotoftp) SwitchButton switch_alarm_videotoftp;//报警录像保存至FTP
    @BindView(R.id.switch_alarm_snaptoftp) SwitchButton switch_alarm_snaptoftp;//报警抓拍保存至FTP
    @BindView(R.id.rl_config_ftp) RelativeLayout rl_config_ftp; //配置FTP

    private HiChipDefines.HI_P2P_S_SD_INFO sd_info;
    private HiChipDefines.ALARMTOSOUND_TYPE mAlarmToSoundType;
    private HiChipDefines.HI_P2P_S_ALARM_PARAM param;
    private HiChipDefines.HI_P2P_SNAP_ALARM snapParam;
    private int mVoiceType;
    private int mTime;
    private static final int ANIM_DURATION = 350;
    @BindView(R.id.rl_config_email) RelativeLayout rl_config_email;// 配置Eamil
    @BindView(R.id.ll_alarm_snap_num) LinearLayout ll_alarm_snap_num;//图片抓拍张数设置(只有海视且支持能力集的才显示)
    @BindView(R.id.rl_snap_num) RelativeLayout rl_snap_num;
    @BindView(R.id.tv_snap_num) TextView tv_snap_num;

    @BindView(R.id.ll_root_alarm_action) LinearLayout ll_root_alarm_action;
    @BindView(R.id.scrollview) ScrollView scrollview;
    @BindView(R.id.tv_device_alarm) TextView tv_device_alarm;
    private boolean mIsV10V6=false;
    @BindView(R.id.rl_adjust_voice_alarm) RelativeLayout rl_adjust_voice_alarm;//调节声音报警
    @BindView(R.id.tv_voice_alarm_sensi) TextView tv_voice_alarm_sensi;

    private boolean mIsHaveSDCard = false;//是否有SD card
    private boolean mIsHaveAlarmLinkage = false;//是否有警号联动
    private boolean mAlarmActionEnable=false;//报警联动是否可用   true 为可用

    @Override
    protected int setLayoutId() {
        return R.layout.activity_alarm_manageandnoti;
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        getIntentData();
        initViewAndData();
        setOnListeners();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mMyCamera != null) {
            mMyCamera.registerIOSessionListener(this);
            //发送移动侦测报警命令
            HiChipDefines.HI_P2P_S_MD_PARAM mdparam = new HiChipDefines.HI_P2P_S_MD_PARAM(0, new HiChipDefines.HI_P2P_S_MD_AREA(HiChipDefines.HI_P2P_MOTION_AREA_1, 0, 0, 0, 0, 0, 0));
            mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_MD_PARAM, mdparam.parseContent());
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mMyCamera != null) {
            mMyCamera.unregisterIOSessionListener(this);
        }
    }

    private void setOnListeners() {
        switch_btn_push.setOnCheckedChangeListener(this);
//      switch_btn_alarm_linkage.setOnCheckedChangeListener(this);
        switch_voice_alarm.setOnCheckedChangeListener(this);
        switch_btn_vmd.setOnCheckedChangeListener(this);


        rl_adjust_vmd.setOnClickListener(this);
        rl_alarm_voice_type.setOnClickListener(this);
        rl_alarm_time.setOnClickListener(this);
        rl_config_email.setOnClickListener(this);
        rl_config_ftp.setOnClickListener(this);
        rl_snap_num.setOnClickListener(this);

        rl_adjust_voice_alarm.setOnClickListener(this);
    }

    private void initViewAndData() {
        initTopView();
        if (mMyCamera.getPushState() > 0) {
            switch_btn_push.setChecked(true);
        } else {
            switch_btn_push.setChecked(false);
        }
    }

    private void initTopView() {
        title.setTitle(getString(R.string.alarm_manage_notifi));
        title.setButton(TitleView.NAVIGATION_BUTTON_LEFT);
        title.setNavigationBarButtonListener(new TitleView.NavigationBarButtonListener() {
            @Override
            public void OnNavigationButtonClick(int which) {
                switch (which) {
                    case TitleView.NAVIGATION_BUTTON_LEFT:
                        finish();
                        break;
                }
            }
        });
    }

    private void getIntentData() {
        String str_uid = getIntent().getStringExtra(HiDataValue.EXTRAS_KEY_UID);
        if (!TextUtils.isEmpty(str_uid)) {
            for (MyCamera camera : HiDataValue.CameraList) {
                if (str_uid.equals(camera.getUid())) {
                    mMyCamera = camera;
                    break;
                }
            }
        }
        if (mMyCamera == null) {
            finish();
            return;
        }
        //发送命令获取是否有SD卡
        if (mMyCamera.getCommandFunction(HiChipDefines.HI_P2P_GET_SD_INFO)) {
            mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_SD_INFO, new byte[0]);
        }
        //发送声音报警
        if (mMyCamera.getCommandFunction(HiChipDefines.HI_P2P_GET_AUDIO_ALM_PARAM)) {
            mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_AUDIO_ALM_PARAM, new byte[0]);
        }
        //如果支持警号联动 就发警号联动命令
        if (mMyCamera.getCommandFunction(HiChipDefines.HI_P2P_GET_ALARMTOSOUND)) {
            mIsHaveAlarmLinkage = true;
            mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_ALARMTOSOUND, new byte[0]);
            ll_root_alarm_linkage.setVisibility(View.VISIBLE);
        }
        //发送 获取报警参数命令
        if (mMyCamera.getCommandFunction(HiChipDefines.HI_P2P_GET_ALARM_PARAM)) {
            mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_ALARM_PARAM, new byte[0]);
        }

        if (mMyCamera.getChipVersion() == HiDeviceInfo.CHIP_VERSION_HISI && mMyCamera.getCommandFunction(HiChipDefines.HI_P2P_GET_SNAP_ALARM_PARAM)) {
            mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_SNAP_ALARM_PARAM, null);
            ll_alarm_snap_num.setVisibility(View.VISIBLE);
        }


    }

    private boolean handTipAndScroll(boolean isChecked,SwitchButton  switchBtn) {
        if(!mAlarmActionEnable){
            showDialog_1();
            switchBtn.setChecked(!isChecked);
            return true;
        }
        return false;
    }

    private  int spaceTime = 400;//时间间隔
    private  long lastClickTime = 0;//上次点击的时间

    public  boolean isFastClick() {
        long currentTime = System.currentTimeMillis();
        boolean isFastClick = false;
        if (currentTime - lastClickTime > spaceTime) {
            isFastClick = false;
        } else {
            isFastClick = true;
        }
        lastClickTime = currentTime;
        return isFastClick;
    }


    @Override
    public void onCheckedChanged(CompoundButton view, boolean isChecked) {
        if(isFastClick()){//防止快速点击,收缩View 时会有问题。
            view.setChecked(!isChecked);
            return;
        }
        switch (view.getId()) {
            case R.id.switch_btn_push:
                handSwiBtnPush(isChecked);
                break;
            case R.id.switch_btn_vmd://移动侦测报警
                handVMD(isChecked);
                break;
            case R.id.switch_voice_alarm://声音报警
                if (!isChecked && !switch_btn_vmd.isChecked()) {
                    ll_root_alarm_action.setAlpha(0.5f);
                    mAlarmActionEnable=false;
                }
                if(isChecked){
                    if(!mAlarmActionEnable){
                        ll_root_alarm_action.setAlpha(1f);
                        mAlarmActionEnable=true;
                    }
                    animViewDisplay(rl_adjust_voice_alarm,0, HiTools.dip2px(this, 50));
                }else {
                    animViewDisplay(rl_adjust_voice_alarm,HiTools.dip2px(this, 50),0);
                }

                voiceParam.enable = isChecked ? 1 : 0;
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_AUDIO_ALM_PARAM, voiceParam.parseContent());
                break;
            case R.id.switch_btn_alarm_linkage:
                if(handTipAndScroll(isChecked,switch_btn_alarm_linkage)) return;
                if (mAlarmToSoundType != null) {
                    handAlarmLinkAge(isChecked);
                }
                break;
            case R.id.switch_alarm_snaptosdcard://报警抓拍至SD卡
                if(!mIsHaveSDCard){
                    switch_alarm_snaptosdcard.setChecked(!isChecked);
                    HiToast.showToast(this,getString(R.string.insert_sd_card));
                    return;
                }
                if (handTipAndScroll(isChecked,switch_alarm_snaptosdcard)) return;
                param.u32SDSnap = isChecked ? 1 : 0;
                param.u32SDRec = switch_alarm_videotosdcard.isChecked() ? 1 : 0;
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_ALARM_PARAM, param.parseContent());
                break;
            case R.id.switch_alarm_videotosdcard://报警录像至SD卡
                if(!mIsHaveSDCard){
                    switch_alarm_videotosdcard.setChecked(!isChecked);
                    HiToast.showToast(this,getString(R.string.insert_sd_card));
                    return;
                }
                if (handTipAndScroll(isChecked,switch_alarm_videotosdcard)) return;
                if(!isChecked){
                    if(!mIsV10V6&&switch_alarm_videotoftp.isChecked()){
                        NiftyDialogBuilder dialog=NiftyDialogBuilder.getInstance(this);
                        dialog.withMessageLayoutHWrapW(HiTools.dip2px(this,300));
                        dialog.withTitle(getString(R.string.tip_reminder)).withMessage(getString(R.string.close_two_item_one)+"\n\n"+getString(R.string.close_two_item_two));
                        dialog.withButton1Text(getString(R.string.cancel)).withButton2Text(getString(R.string.close_term));
                        dialog.withButton1TextColor(getResources().getColor(R.color.color_theme_blue));
                        dialog.withButton2TextColor(getResources().getColor(R.color.color_pass_word));
                        dialog.isCancelable(false);
                        dialog.isCancelableOnTouchOutside(false);
                        dialog.show();
                        dialog.setButton2Click(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                switch_alarm_videotoftp.setChecked(false);
                                dialog.dismiss();
                            }
                        });
                        dialog.setButton1Click(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                switch_alarm_videotosdcard.setChecked(true);
                                dialog.dismiss();
                            }
                        });
                    }
                }
                param.u32SDSnap = switch_alarm_snaptosdcard.isChecked() ? 1 : 0;
                param.u32SDRec = isChecked ? 1 : 0;
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_ALARM_PARAM, param.parseContent());
                break;
            case R.id.switch_alarm_snaptoemail: //报警抓怕发送至Email
                if(handTipAndScroll(isChecked,switch_alarm_snaptoemail)) return;
                if (param != null) {
                    handSnapToEmail(isChecked);
                }
                break;
            case R.id.switch_alarm_videotoftp://报警录像保存至FTP
                if (handTipAndScroll(isChecked,switch_alarm_videotoftp)) return;
                if (isChecked) {
                    if (rl_config_ftp.getVisibility() == View.GONE) {
                        animViewDisplay(rl_config_ftp, 0, HiTools.dip2px(this, 50));
                    }
                } else {
                    if (!switch_alarm_snaptoftp.isChecked() && rl_config_ftp.getVisibility() == View.VISIBLE) {
                        animViewDisplay(rl_config_ftp, HiTools.dip2px(this, 50), 0);
                    }
                }
                param.u32FtpRec = isChecked ? 1 : 0;
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_ALARM_PARAM, param.parseContent());
                break;
            case R.id.switch_alarm_snaptoftp://报警抓拍保存至FTP
                if (handTipAndScroll(isChecked,switch_alarm_snaptoftp)) return;
                if (isChecked) {
                    if (rl_config_ftp.getVisibility() == View.GONE) {
                        animViewDisplay(rl_config_ftp, 0, HiTools.dip2px(this, 50));
                    }
                } else {
                    if (!switch_alarm_videotoftp.isChecked() && rl_config_ftp.getVisibility() == View.VISIBLE) {
                        animViewDisplay(rl_config_ftp, HiTools.dip2px(this, 50), 0);
                    }
                }
                param.u32FtpSnap = isChecked ? 1 : 0;
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_ALARM_PARAM, param.parseContent());
                break;
        }
    }

    private void handSnapToEmail(boolean isChecked) {
        if (isChecked) {
            animViewDisplay(rl_config_email, 0, HiTools.dip2px(this, 50));
        } else {
            animViewDisplay(rl_config_email, HiTools.dip2px(this, 50), 0);
        }
        param.u32EmailSnap = isChecked ? 1 : 0;
        mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_ALARM_PARAM, param.parseContent());
    }

    private void handAlarmLinkAge(boolean isChecked) {
        if (isChecked) {
            ll_alarm_linkage_content.setVisibility(View.VISIBLE);
            animViewDisplay(ll_alarm_linkage_content, 0, HiTools.dip2px(this, 90));
        } else {
            animViewDisplay(ll_alarm_linkage_content, HiTools.dip2px(this, 90), 0);
        }
        byte enable = isChecked ? (byte) 1 : (byte) 0;
        mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_ALARMTOSOUND, HiChipDefines.ALARMTOSOUND_TYPE.parseContent(enable, mAlarmToSoundType.SoundType, mAlarmToSoundType.SoundType));


    }

    private void handVMD(boolean isChecked) {
        if (isChecked) {
            animViewDisplay(rl_adjust_vmd, 0, HiTools.dip2px(this, 50));
            if(!mAlarmActionEnable){
                ll_root_alarm_action.setAlpha(1f);
                mAlarmActionEnable=true;
            }
        } else {
            animViewDisplay(rl_adjust_vmd, HiTools.dip2px(this, 50), 0);
            if (!switch_voice_alarm.isChecked()) {
                ll_root_alarm_action.setAlpha(0.5f);
                mAlarmActionEnable=false;
            }
        }
        if (md_param != null) {
            md_param.struArea.u32Enable = isChecked ? 1 : 0;
            mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_MD_PARAM, md_param.parseContent());
        }

    }

    private void handSwiBtnPush(boolean isChecked) {
        if (isChecked) {
            if (!switch_voice_alarm.isChecked() && !switch_btn_vmd.isChecked()) {
                switch_btn_push.setChecked(false);
                showDialog_1();
                return;
            }
        }
        if (mChecked) {
            mChecked = false;
            return;
        }
        if (HiDataValue.XGToken == null) {
            if (HiDataValue.ANDROID_VERSION >= 6) {
                if (!HiTools.checkPermission(AlarmManageAndNotiActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    ActivityCompat.requestPermissions(AlarmManageAndNotiActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
                }
            }
            HiDataValue.XGToken = XGPushConfig.getToken(AlarmManageAndNotiActivity.this);
            if (HiDataValue.XGToken == null) {
                switch_btn_push.setChecked(!switch_btn_push.isChecked());
                HiToast.showToast(AlarmManageAndNotiActivity.this, "null token");
                return;
            }
        }
        showjuHuaDialog();
        mMyCamera.bindPushState(switch_btn_push.isChecked(), bindPushResult);
    }

    private void showDialog_1() {
        NiftyDialogBuilder dialog = NiftyDialogBuilder.getInstance(this);
        dialog.withTitle(getString(R.string.open_device_alarm)).withMessage(getString(R.string.open_any_king));
        dialog.withMessageLayoutHWrapW(HiTools.dip2px(this, 280));
        dialog.withButOnlyOne(getString(R.string.all_right), getResources().getColor(R.color.color_theme_blue), 17);
        dialog.show();
        dialog.setButton2Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                ObjectAnimator colorAnim = ObjectAnimator.ofInt(ll_content_device_alarm, "backgroundColor", getResources().getColor(R.color.white), Color.parseColor("#5545A7E6"), getResources().getColor(R.color.white));
                colorAnim.setDuration(1500);
                colorAnim.setEvaluator(new ArgbEvaluator());
                colorAnim.setRepeatCount(1);
                colorAnim.start();
                scrollview.smoothScrollTo(scrollview.getScrollX(),tv_device_alarm.getScrollY());
            }
        });
    }

    private MyCamera.OnBindPushResult bindPushResult = new MyCamera.OnBindPushResult() {

        @Override
        public void onBindSuccess(MyCamera camera) {
            Message msg = mHandler.obtainMessage();
            msg.what = HANDLE_MESSAGE_BIND_SUCCESS;
            msg.obj = camera;
            mHandler.sendMessage(msg);
        }

        @Override
        public void onBindFail(MyCamera camera) {
            Message msg = mHandler.obtainMessage();
            msg.what = HANDLE_MESSAGE_BIND_FAIL;
            mHandler.sendMessage(msg);
        }

        @Override
        public void onUnBindSuccess(MyCamera camera) {
            Message msg = mHandler.obtainMessage();
            msg.what = HANDLE_MESSAGE_UNBIND_SUCCESS;
            mHandler.sendMessage(msg);
        }

        @Override
        public void onUnBindFail(MyCamera camera) {
            Message msg = mHandler.obtainMessage();
            msg.what = HANDLE_MESSAGE_UNBIND_FAIL;
            mHandler.sendMessage(msg);
        }
    };

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLE_MESSAGE_BIND_SUCCESS:
                    MyCamera myCamera = (MyCamera) msg.obj;
                    dismissjuHuaDialog();
                    if (!myCamera.handSubXYZ()) {
                        if (myCamera.handSubWTU()) {
                            myCamera.setServerData(HiDataValue.CAMERA_ALARM_ADDRESS_122);
                        }else {
                            myCamera.setServerData(HiDataValue.CAMERA_ALARM_ADDRESS);
                        }
                    } else {
                        myCamera.setServerData(HiDataValue.CAMERA_ALARM_ADDRESS_THERE);
                    }
                    mMyCamera.updateInDatabase(AlarmManageAndNotiActivity.this);
                    sendServer(myCamera);
                    sendRegister();
                    break;
                case HANDLE_MESSAGE_BIND_FAIL:
                    HiToast.showToast(AlarmManageAndNotiActivity.this, getString(R.string.tip_open_faild));
                    mChecked = true;
                    switch_btn_push.setChecked(false);
                    dismissjuHuaDialog();
                    mMyCamera.updateInDatabase(AlarmManageAndNotiActivity.this);
                    break;
                case HANDLE_MESSAGE_UNBIND_SUCCESS:
                    sendUnRegister();
                    mMyCamera.setPushState(HiDataValue.DEFAULT_PUSH_STATE);
                    dismissjuHuaDialog();
                    mMyCamera.updateInDatabase(AlarmManageAndNotiActivity.this);
                    break;
                case HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL:
                    if (msg.arg2 == 0) {//成功
                        handReceiveIOCTRLSuccess(msg);
                    } else {
                        handReceiveIOCTRLFail(msg);
                    }
                    break;
            }

        }
    };

    private void handReceiveIOCTRLFail(Message msg) {
    }

    private void handReceiveIOCTRLSuccess(Message msg) {
        Bundle bundle = msg.getData();
        byte[] data = bundle.getByteArray(HiDataValue.EXTRAS_KEY_DATA);
        switch (msg.arg1) {
            case HiChipDefines.HI_P2P_GET_SNAP_ALARM_PARAM:
                snapParam = new HiChipDefines.HI_P2P_SNAP_ALARM(data);
                tv_snap_num.setText(snapParam.u32Number + "");
                break;
            case HiChipDefines.HI_P2P_GET_ALARM_PARAM:
                param = new HiChipDefines.HI_P2P_S_ALARM_PARAM(data);
                switch_alarm_snaptosdcard.setChecked(param.u32SDSnap == 1 ? true : false);
                switch_alarm_videotosdcard.setChecked(param.u32SDRec == 1 ? true : false);
                switch_alarm_snaptoemail.setChecked(param.u32EmailSnap == 1 ? true : false);
                switch_alarm_videotoftp.setChecked(param.u32FtpRec == 1 ? true : false);
                switch_alarm_snaptoftp.setChecked(param.u32FtpSnap == 1 ? true : false);
                if ((param.u32FtpRec == 1 || param.u32FtpSnap == 1) && rl_config_ftp.getVisibility() == View.GONE) {
                    animViewDisplay(rl_config_ftp, 0, HiTools.dip2px(this, 50));
                }

                if (param.u32EmailSnap == 1 && rl_config_email.getVisibility() == View.GONE) {
                    animViewDisplay(rl_config_email, 0, HiTools.dip2px(this, 50));
                }

                switch_alarm_snaptosdcard.setOnCheckedChangeListener(this);
                switch_alarm_videotosdcard.setOnCheckedChangeListener(this);
                switch_alarm_snaptoemail.setOnCheckedChangeListener(this);
                switch_alarm_videotoftp.setOnCheckedChangeListener(this);
                switch_alarm_snaptoftp.setOnCheckedChangeListener(this);
                break;
            case HiChipDefines.HI_P2P_GET_ALARMTOSOUND:
                mAlarmToSoundType = new HiChipDefines.ALARMTOSOUND_TYPE(data);
                mVoiceType = mAlarmToSoundType.SoundType;
                mTime = mAlarmToSoundType.TimeLast;
                switch_btn_alarm_linkage.setChecked(mAlarmToSoundType.enable == 1 ? true : false);
                switch_btn_alarm_linkage.setOnCheckedChangeListener(this);
                if (mAlarmToSoundType.enable == 1) {
                    animViewDisplay(ll_alarm_linkage_content,0,HiTools.dip2px(this,90));
                }
                tv_voice_type.setText(mAlarmToSoundType.SoundType == 0 ? getString(R.string.alarm_alarm_sound) : getString(R.string.alarm_barking));
                tv_alarm_time.setText(mAlarmToSoundType.TimeLast + getString(R.string.sends));
                break;
            case HiChipDefines.HI_P2P_GET_MD_PARAM:
                md_param = new HiChipDefines.HI_P2P_S_MD_PARAM(data);
                if (md_param.struArea.u32Area == HiChipDefines.HI_P2P_MOTION_AREA_1) {
                    switch_btn_vmd.setChecked(md_param.struArea.u32Enable == 1 ? true : false);
                    tv_sensitivity.setText(getString(R.string.sensi) + md_param.struArea.u32Sensi);
                }
                break;
            case HiChipDefines.HI_P2P_GET_AUDIO_ALM_PARAM:
                voiceParam = new HiChipDefines.HI_P2P_S_ALM_PARAM(data);
                tv_voice_alarm_sensi.setText(getString(R.string.sensi)+voiceParam.sensi);
                switch_voice_alarm.setChecked(voiceParam.enable == 1 ? true : false);
                break;
            case HiChipDefines.HI_P2P_GET_SD_INFO:
                sd_info = new HiChipDefines.HI_P2P_S_SD_INFO(data);
                mIsHaveSDCard = sd_info.u32Status == 1 ? true : false;
                rl_alarm_snap_to_sdcard.setAlpha(mIsHaveSDCard?1.0f:0.5f);
                rl_alarm_video_to_sdcard.setAlpha(mIsHaveSDCard?1.0f:0.5f);
                if (!mIsHaveSDCard) {
                    HiChipDefines.HI_P2P_GET_DEV_INFO_EXT deviceInfo = mMyCamera.getDeciveInfo();
                    String softVersion = Packet.getString(deviceInfo.aszSystemSoftVersion);
                    if (!TextUtils.isEmpty(softVersion)) {
                        String[] strs = softVersion.split("\\.");
                        if ("V10".equals(strs[0]) || "V6".equals(strs[0])) {
                            mIsV10V6=true;
                            rl_alarm_video_to_ftp.setVisibility(View.VISIBLE);
                        } else {
                            rl_alarm_video_to_ftp.setVisibility(View.GONE);
                        }
                    }
                }
                break;
        }

    }


    protected void sendServer(MyCamera mCamera) {
        if (mCamera.getServerData() == null) {
            mCamera.setServerData(HiDataValue.CAMERA_ALARM_ADDRESS);
            mCamera.updateServerInDatabase(this);
        }
        if (!mCamera.getCommandFunction(CamHiDefines.HI_P2P_ALARM_ADDRESS_SET)) {
            return;
        }
        if (mCamera.push != null) {
            String[] strs = mCamera.push.getPushServer().split("\\.");
            if (strs.length == 4 && isInteger(strs[0]) && isInteger(strs[1]) && isInteger(strs[2]) && isInteger(strs[3])) {
                byte[] info = CamHiDefines.HI_P2P_ALARM_ADDRESS.parseContent(mCamera.push.getPushServer());
                mCamera.sendIOCtrl(CamHiDefines.HI_P2P_ALARM_ADDRESS_SET, info);
            }
        }
    }

    /*
     *推荐，速度最快 判断是否为整数
     * @param str 传入的字符串
     * @return 是整数返回true,否则返回false
     */
    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    private void sendRegister() {
        if (mMyCamera.getPushState() == 1) {
            return;
        }
        if (!mMyCamera.getCommandFunction(CamHiDefines.HI_P2P_ALARM_TOKEN_REGIST)) {
            return;
        }
        byte[] info = CamHiDefines.HI_P2P_ALARM_TOKEN_INFO.parseContent(0, mMyCamera.getPushState(), (int) (System.currentTimeMillis() / 1000 / 3600), mMyCamera.getPushState() > 0 ? 1 : 0);
        mMyCamera.sendIOCtrl(CamHiDefines.HI_P2P_ALARM_TOKEN_REGIST, info);
    }

    private void sendUnRegister() {
        if (mMyCamera.getPushState() == 0) {
            return;
        }
        if (!mMyCamera.getCommandFunction(CamHiDefines.HI_P2P_ALARM_TOKEN_UNREGIST)) {
            return;
        }
        byte[] info = CamHiDefines.HI_P2P_ALARM_TOKEN_INFO.parseContent(0, mMyCamera.getPushState(), (int) (System.currentTimeMillis() / 1000 / 3600), mMyCamera.getPushState() > 0 ? 1 : 0);
        mMyCamera.sendIOCtrl(CamHiDefines.HI_P2P_ALARM_TOKEN_UNREGIST, info);
    }


    @Override
    public void receiveSessionState(HiCamera arg0, int arg1) {
    }

    @Override
    public void receiveIOCtrlData(HiCamera arg0, int arg1, byte[] arg2, int arg3) {
        if (arg0 != mMyCamera) return;
        Bundle bundle = new Bundle();
        bundle.putByteArray(HiDataValue.EXTRAS_KEY_DATA, arg2);
        Message msg = mHandler.obtainMessage();
        msg.what = HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL;
        msg.obj = arg0;
        msg.arg1 = arg1;
        msg.arg2 = arg3;
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_adjust_vmd://调节移动侦测
                Intent intent = new Intent(AlarmManageAndNotiActivity.this, AdjustVMDActivity.class);
                intent.putExtra(HiDataValue.EXTRAS_KEY_UID, mMyCamera.getUid());
                startActivity(intent);
                break;
            case R.id.rl_alarm_voice_type:
                if(!mAlarmActionEnable){
                    showDialog_1();
                    return;
                }
                intent = new Intent(AlarmManageAndNotiActivity.this, AlarmVoiceTypeActivity.class);
                intent.putExtra("mVoiceType", mVoiceType);
                startActivityForResult(intent, 110);
                break;
            case R.id.rl_alarm_time:
                if(!mAlarmActionEnable){
                    showDialog_1();
                    return;
                }
                intent = new Intent(AlarmManageAndNotiActivity.this, AlarmSoundTimeActivity.class);
                intent.putExtra("mTime", mTime);
                startActivityForResult(intent, 119);
                break;
            case R.id.rl_config_email:
                if(!mAlarmActionEnable){
                    showDialog_1();
                    return;
                }
                intent = new Intent(AlarmManageAndNotiActivity.this, EmailSettingActivity.class);
                intent.putExtra(HiDataValue.EXTRAS_KEY_UID, mMyCamera.getUid());
                startActivity(intent);
                break;
            case R.id.rl_config_ftp:
                if(!mAlarmActionEnable){
                    showDialog_1();
                    return;
                }
                intent = new Intent(AlarmManageAndNotiActivity.this, FtpSettingActivity.class);
                intent.putExtra(HiDataValue.EXTRAS_KEY_UID, mMyCamera.getUid());
                startActivity(intent);
                break;
            case R.id.rl_snap_num:
                if(!mAlarmActionEnable){
                    showDialog_1();
                    return;
                }
                intent = new Intent(AlarmManageAndNotiActivity.this, AlarmSnapNumActivity.class);
                String str_num = tv_snap_num.getText().toString().trim();
                int num = Integer.parseInt(str_num);
                intent.putExtra("num", num);
                startActivityForResult(intent, 999);
                break;
            case R.id.rl_adjust_voice_alarm:
                if(!mAlarmActionEnable){
                    showDialog_1();
                    return;
                }
                intent=new Intent(AlarmManageAndNotiActivity.this,AdjustVoiceAlarmActivity.class);
                intent.putExtra(HiDataValue.EXTRAS_KEY_UID,mMyCamera.getUid());
                startActivityForResult(intent,9998);
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 9998:
                    String rate=data.getStringExtra("rate");
                    tv_voice_alarm_sensi.setText(getString(R.string.sensi)+rate);
                    break;
                case 999:
                    int num = data.getIntExtra("num", 1);
                    tv_snap_num.setText(num + "");
                    snapParam.u32Number = num;
                    snapParam.u32Interval = snapParam.u32Interval < 5 ? 5 : snapParam.u32Interval;
                    mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_SNAP_ALARM_PARAM, snapParam.parseContent());
                    break;
                case 110:
                    mVoiceType = data.getIntExtra("mVoiceType", 0);
                    tv_voice_type.setText(mVoiceType == 0 ? getString(R.string.alarm_alarm_sound) : getString(R.string.alarm_barking));
                    int enable = switch_btn_alarm_linkage.isChecked() ? 1 : 0;
                    mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_ALARMTOSOUND, HiChipDefines.ALARMTOSOUND_TYPE.parseContent((byte) enable, (byte) mVoiceType, (byte) mTime));
                    break;
                case 119:
                    mTime = data.getIntExtra("mTime", 5);
                    tv_alarm_time.setText(mTime + getString(R.string.sends));
                    enable = switch_btn_alarm_linkage.isChecked() ? 1 : 0;
                    mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_ALARMTOSOUND, HiChipDefines.ALARMTOSOUND_TYPE.parseContent((byte) enable, (byte) mVoiceType, (byte) mTime));
                    break;
            }
        }
    }

    private void animViewDisplay(View view, int start, int end) {
        if (start == 0) {
            view.setVisibility(View.VISIBLE);
        }
        ValueAnimator animator = ValueAnimator.ofInt(start, end);
        animator.setDuration(ANIM_DURATION);
        animator.setInterpolator(new AccelerateInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int value = (int) animation.getAnimatedValue();
                view.getLayoutParams().height = value;
                view.requestLayout();
            }
        });
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                if (start != 0) {
                    view.setVisibility(View.GONE);
                }
            }
        });
        animator.start();
    }


}
